package com.medical.smartcare.database;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.medical.smartcare.AppConfig;

public class DatabaseHelper extends SQLiteOpenHelper
{
	private static final String TAG = DatabaseHelper.class.getSimpleName();

	private static final Lock LOCK = new ReentrantLock();

	public DatabaseHelper(Context context)
	{
		super(context, AppConfig.SQLITE_DATABASE_NAME, null, AppConfig.SQLITE_DATABASE_VERSION);
	}

	@Override
	public void onOpen(SQLiteDatabase db)
	{
		try
		{
			LOCK.lock();
			{
				super.onOpen(db);

				if (!db.isReadOnly())
					db.execSQL("PRAGMA foreign_keys=ON;"); // Enable foreign key constraints
			}
			LOCK.unlock();
		}
		catch (Exception e)
		{
			Log.e(TAG, e.toString());
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db)
	{
		try
		{
			LOCK.lock();
			{
				// for (int i = 0; i < AppConfig.SQLITE_CREATE_TABLE_COMMAND.length; i++)
				// {
				// db.execSQL(AppConfig.SQLITE_CREATE_TABLE_COMMAND[i]);
				// }
			}
			LOCK.unlock();
		}
		catch (Exception e)
		{
			Log.d(TAG, e.toString());
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
		// TODO Auto-generated method stub
	}

	/************************/
	public long insertData(String tableName, ContentValues contentValues)
	{
		long lastInsertRowId = -1;
		try
		{
			SQLiteDatabase db = getWritableDatabase();
			LOCK.lock();
			{
				lastInsertRowId = db.insert(tableName, null, contentValues);
			}
			LOCK.unlock();
		}
		catch (Exception ex)
		{
			Log.e(TAG, ex.toString());
		}
		return lastInsertRowId;
	}
}